package com.levi.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁
 */
public class ReentrantLockTest {
    public static void main(String[] args) {
       /* Tiket tiket = new Tiket();
        //创建10个线程
        for (int i = 0; i < 10; i++) {
            new Thread(()-> {
                tiket.sale();
            }).start();
        }*/
        T t = new T();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                t.sale();
            }).start();
        }
    }
}

class Tiket {
    //总票数
    private int num = 5;
    //卖出的票数
    private int salenum = 1;
    //创建可重入锁，非公平锁
    Lock lock = new ReentrantLock();
    /**
     * 买票的方法
     */
    public void sale() {
        //加锁
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName());
            if (num>0) {
                num--;
                System.out.println("卖出"+(salenum++) +"还剩"+num+"张票");
            }else {
                System.out.println("票买完了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放锁
            lock.unlock();
        }

    }
}


class T{
    private int num = 5;//总票数
    private int saleNum = 0;//卖出的票数
    private final Lock lock = new ReentrantLock();

    /**
     * 一次买一张票
     */
    public void sale() {
        lock.lock();
        try {
            if (num >0) {
                num--;
                saleNum++;
                System.out.println(Thread.currentThread().getName()+"#卖出"+saleNum+"张票,还剩"+num+"张票");
            }else{
                System.out.println(Thread.currentThread().getName()+"#票卖完了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}